import re
from flask import Blueprint,jsonify,request
import json
from db import db
from werkzeug.security import generate_password_hash,check_password_hash
bp_ausers = Blueprint("ausers",__name__)

#初始化数据
@bp_ausers.route('/reg')
def reg():
    #手动添加一个账号加密
    password = generate_password_hash('123')
    sql1 = "insert into auser values(0,'张珊','%s','村阿萨德要奇才')"%(password)
    db.insert(sql1)

    sql2 = "insert into auser values(0,'李思','%s','阿萨德啊名')"%(password)

    db.insert(sql2)
    return 'ok'


#登录接口
@bp_ausers.route('/login',methods=['POST'])
def login():
    #获取用户名密码
    data = request.data
    if data:
        data = json.loads(data)
    else:
        data = request.form
    #去数据查询根据用户名
    sql = "select * from auser where username='%s'"%(data['username'])
    res = db.get_one(sql)
    #比对密码
    if res:
        #返回结果，userid
        if check_password_hash(res['password'],data['password']):
            return jsonify({"code":200,'userid':res['id'],'username':res['username'],'sign':res['sign']})
        else:
            return jsonify({"code":10010,'mes':'密码错误'})
    return jsonify({"code":10011,'mes':'用户不存在'})


@bp_ausers.route('/articleM',methods=['POST','GET'])
def articleM():
    if request.method == "POST":
        #获取用户输入
        data = request.data
        if data:
            data = json.loads(request.data)
        else:
            data = request.form
        
        #构造sql添加
        sql = "insert into article(title,content,userid) values('%s','%s',%d)"%(data['title'],data['content'],int(data['userid']))
        db.insert(sql)
        #返回结果
        return jsonify({"code":200})
    else:
        #判断获取所有文章还是我的文章
        uid = int(request.args.get('uid'))
        if uid>0:
            sql = "select * from article where userid=%d"%(int(uid))
        else:
            sql = "select * from article"
        res = db.get_all(sql)
        return jsonify({"code":200,'list':res})